<?php
//------------------------
// 商品分类模型
//-------------------------
namespace app\common\model;

use think\Model;
use think\Cache;

class GoodsCate extends Model{

	// 获取分类树
	public function getTree(){
		$data = $this->select()->toArray();
		return $this->_reSort($data);
	}

	// 无限级向下递归制作分类树
	private function _reSort($data, $parent_id=0, $level=0, $isClear=TRUE){
		static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v){
			if($v['parent_id'] == $parent_id){
				$v['level'] = $level;
				$ret[] = $v;
				$this->_reSort($data, $v['id'], $level+1, FALSE);
			}
		}
		return $ret;
	}



	// 获取子分类
	public function getChildren($id){
		$data = $this->select()->toArray();
		return $this->_children($data, $id);
	}

	// 无限级向下递归获取子分类
	private function _children($data, $parent_id=0, $isClear=TRUE){
		static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v){
			if($v['parent_id'] == $parent_id){
				$ret[] = $v['id'];
				$this->_children($data, $v['id'], FALSE);
			}
		}
		return $ret;
	}

	// 获取三级导航
	public function getNavCatData(){
		$data = array();
		// 缓存中读取
		$data = Cache::get('navCat');

		if ($data) {
			return $data;
		} else {
			// 先取出所有的分类
			$allCat = $this->select()->toArray();

			// 再从所有的分类中取出顶级的
			foreach ($allCat as $k => $v){
				if($v['parent_id'] == 0){
					// 循环找这个顶级分类的二级分类
					foreach ($allCat as $k1 => $v1){
						if($v1['parent_id'] == $v['id']){
							foreach ($allCat as $k2 => $v2){
								if($v2['parent_id'] == $v1['id']){
									$v1['children'][] = $v2;
								}
							}
							$v['children'][] = $v1;
						}
					}
					$data[] = $v;
				}
			}

			Cache::set('navCat',$data,3600);
			// halt($data);
			return $data;

		}

		
	}
}